<template>
  <div class="container">
    <van-sticky>
      <div class="head">
        <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
        <div class="title">绑卡</div>
      </div>
    </van-sticky>
    <div class="warp">
      <van-form>
        <van-field label-width="50" v-model="paramsData.cardNo" name="卡号" label="卡号" placeholder="请输入卡号"
          :rules="[{ required: true, message: '请输入卡号' }]">
        </van-field>
        <van-field label-width="50" v-model="paramsData.cardPwd" name="卡密" label="卡密" placeholder="请输入卡密"
          type="password" :rules="[{ required: true, message: '请输入卡密' }]">
        </van-field>
        <div class="btn">
          <van-button class="left" round block type="info" native-type="submit" @click="scanQRCode"><van-icon
              :loading="loading" style="margin-right: 5px" name="scan" />绑定</van-button>
          <van-button class="right" round block type="info" @click="confirmData">绑定</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import { Toast } from "vant";
import plantAPI from "@/api/plant";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      cardNo: '',
      cardPwd: '',
      cardInfo: {},
      datas: "",
      loading: false,
      paramsData: { cardNo: '', cardPwd: '' },
      wxConfigCompleted: false,
    }
  },
  mounted() {

    this.getUrlParams();
    this.getWxConfig();
  },
  beforeDestroy() {
    wx.error(() => { });
  },

  methods: {
    goRegister() {

      // 1. 配置基础参数
      const appId = 'wxf6b22350d8075054'; // 从微信公众平台获取
      const redirectUri = encodeURIComponent('https://xhjzh.life/register'
      );
      // 2. 构造微信授权URL
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?` +
        `appid=${appId}` +
        `&redirect_uri=${redirectUri}` +
        `&response_type=code` + // 固定值，返回 code
        `&scope=snsapi_userinfo` + // 授权类型（snsapi_base 或 snsapi_userinfo）
        `&state=home` + // 自定义参数（可选，可用于存储跳转前的页面路径）
        `#wechat_redirect`; // 固定锚点

      // 3. 跳转到微信授权页面（在新窗口打开，避免当前页历史记录问题）
      window.open(authUrl, '_self'); // 或使用 window.location.href = authUrl

    },
    getUrlParams() {
      // 获取当前页面的查询参数
      const query = window.location.search.substring(1);
      const params = new URLSearchParams(query);
      const cardNo = params.get('cardNo'); // 获取 cardNo 参数值
      const cardPwd = params.get('cardPwd'); // 获取 cardPwd 参数值
      if (cardNo && cardPwd) {
        let token = localStorage.getItem('token')
        if (!token) {
          localStorage.setItem("cardNo", cardNo)
          localStorage.setItem("cardPwd", cardPwd)
          this.goRegister()
          return;
        }
        this.paramsData.cardNo = cardNo
        this.paramsData.cardPwd = cardPwd
        plantAPI.bindCard(this.paramsData).then(res => {
          Toast("绑定成功")
          setTimeout(() => {
            this.$router.push(
              {
                path: '/cardCoupon'
              }
            )
          }, 1000)

        }).catch(err => {
        })
      }
    },
    // async getWxConfig() {
    //   this.loading = true;
    //   const url = window.location.href.split('#')[0];
    //   plantAPI.wxSign({
    //     url
    //   }).then(res => {
    //     wx.config({
    //       debug: false,
    //       appId: "wxf6b22350d8075054",
    //       timestamp: res.data.timestamp.toString(),
    //       nonceStr: res.data.nonceStr,
    //       signature: res.data.signature,
    //       jsApiList: ['scanQRCode']
    //     });
    //     wx.ready(() => {
    //       console.log('微信JS-SDK配置成功');
    //       this.loading = false;
    //     });

    //     wx.error(err => {
    //       console.error('微信JS-SDK配置失败:', err);
    //       this.loading = false;
    //     });
    //   })
    // },
    async getWxConfig() {
      this.loading = true;
      const url = window.location.href.split('#')[0];
      plantAPI.wxSign({ url }).then(res => {
        wx.config({
          debug: false,
          appId: "wxf6b22350d8075054",
          timestamp: res.data.timestamp.toString(),
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
          jsApiList: ['scanQRCode']
        });

        wx.ready(() => {
          console.log('微信JS-SDK配置成功');
          this.wxConfigCompleted = true;  // ✅ 改动1：确保标记就绪
          this.loading = false;
        });

        wx.error(err => {
          console.error('微信JS-SDK配置失败:', err);
          this.wxConfigCompleted = false;  // ✅ 改动2：失败时重置状态
          this.loading = false;
        });
      })
    },
    parseKeyValueString(str) {
      return str.split(',').reduce((obj, pair) => {
        const [key, value] = pair.split(':');
        obj[key] = value;
        return obj;
      }, {});
    },
    // scanQRCode() {
    //   this.loading = true;
    //   if (!wx.scanQRCode) {
    //     Toast.fail("当前环境不支持扫一扫");
    //     return;
    //   }

    //   wx.ready(() => {
    //     wx.scanQRCode({
    //       needResult: 1,
    //       scanType: ["qrCode", "barCode"],
    //       success: (res) => {
    //         const url = new URL(res.resultStr);
    //         this.paramsData.cardNo = url.searchParams.get('cardNo') || '';
    //         this.paramsData.cardPwd = url.searchParams.get('cardPwd') || '';
    //         if (!localStorage.getItem('token')) {
    //           localStorage.setItem("cardNo", this.paramsData.cardNo)
    //           localStorage.setItem("cardPwd", this.paramsData.cardPwd)
    //           this.goRegister()
    //           return;
    //         }
    //         plantAPI.bindCard(this.paramsData)
    //           .then(() => {
    //             Toast("绑定成功");
    //             this.loading = false;
    //             this.$router.push('/cardCoupon');
    //           })
    //           .finally(() => {
    //             this.loading = false;
    //           });
    //       },
    //       fail: (err) => {
    //         console.error('扫描失败:', err);
    //         Toast.fail('扫描失败，请重试');
    //         this.loading = false;
    //       }
    //     });
    //   });

    // },
    scanQRCode() {
      this.loading = true;
      if (!wx.scanQRCode) {
        Toast.fail("当前环境不支持扫一扫");
        this.loading = false;
        return;
      }

      // ✅ 改动3：删除 wx.ready() 包裹，直接执行
      wx.scanQRCode({
        needResult: 1,
        scanType: ["qrCode", "barCode"],
        success: (res) => {
          const url = new URL(res.resultStr);
          this.paramsData.cardNo = url.searchParams.get('cardNo') || '';
          this.paramsData.cardPwd = url.searchParams.get('cardPwd') || '';
          if (!localStorage.getItem('token')) {
            localStorage.setItem("cardNo", this.paramsData.cardNo)
            localStorage.setItem("cardPwd", this.paramsData.cardPwd)
            this.goRegister()
            return;
          }
          plantAPI.bindCard(this.paramsData)
            .then(() => {
              Toast("绑定成功");
              this.loading = false;
              this.$router.push('/cardCoupon');
            })
            .finally(() => {
              this.loading = false;
            });
        },
        fail: (err) => {
          console.error('扫描失败:', err);
          Toast.fail('扫描失败，请重试');
          this.loading = false;
        }
      });
    },
    confirmData() {
      if (!this.paramsData.cardNo || !this.paramsData.cardPwd) {
        this.show = true;
        Toast("请先填写卡号和卡密")
        return;
      }
      plantAPI.bindCard(this.paramsData).then(res => {
        Toast("绑定成功")
        this.$router.push(
          {
            path: '/cardCoupon'
          }
        )
      })
    },
    goBack() {
      this.$router.go(-1)
    },
  }
}
</script>
<style lang="scss" scoped>
::v-deep .van-sticky {
  background: #FFFFFF;

}

.container {
  min-height: 100vh;
  background: rgb(244, 244, 244);

  .head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
      width: 20px;
      height: 20px;
      position: absolute;
      left: 15px;
    }

    .title {
      width: 100%;
      text-align: center;
      font-size: 16px;
      color: #000000;
    }
  }

  .warp {
    width: 351px;
    position: relative;
    padding: 10px 0;
    margin: auto;

    ::v-deep .van-form {
      width: 100%;
      border-radius: 5px;
      background: #fff;
      padding-bottom: 15px;
      padding-top: 10px;
    }

    .btn {
      //position: absolute;
      //bottom: 0;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      padding: 30px 15px 0 15px;
      justify-content: space-between;

      //left: 0;
      //padding: 10px;
      ::v-deep .van-button--info {
        width: 65%;
        border: none;

        height: 40px;

      }

      .right {
        background: #fbc9c6;
      }

      .left {
        //::v-deep .van-button--info{
        width: 30%;
        height: 40px;
        //}
      }

    }
  }


}
</style>
